package dao

import (
	"advertising/internal/dal"
	"advertising/internal/models"
	"context"
	"strings"
	"time"

	"192.168.1.75/go-pkg/helper"
	"gorm.io/gorm"
)

type SupportActivity struct{}

// Create 创建活动
func (SupportActivity) Create(ctx context.Context, db *gorm.DB, name string, startTime, endTime int64, materialIDs, userID, username string) (id string, err error) {
	a := dal.Use(db).SupportActivity

	var data models.SupportActivity
	data.ID, _ = helper.UUID{}.String()
	data.Name = name
	data.StartTime = startTime
	data.EndTime = endTime
	data.MaterialIDs = materialIDs
	data.Status = 1 // 默认启用
	data.CreateUser = userID
	data.CreateUserName = username
	data.CreatedAt = time.Now().Unix()

	err = a.WithContext(ctx).Create(&data)
	if err != nil {
		return "", err
	}
	return data.ID, nil
}

// Update 更新活动
func (SupportActivity) Update(ctx context.Context, db *gorm.DB, id, name string, startTime, endTime int64, materialIDs string) (err error) {
	a := dal.Use(db).SupportActivity

	_, err = a.WithContext(ctx).
		Where(a.ID.Eq(id), a.DeletedAt.Eq(0)).
		Updates(map[string]interface{}{
			a.Name.ColumnName().String():        name,
			a.StartTime.ColumnName().String():   startTime,
			a.EndTime.ColumnName().String():     endTime,
			a.MaterialIDs.ColumnName().String(): materialIDs,
			a.UpdatedAt.ColumnName().String():   time.Now().Unix(),
		})
	return err
}

// Detail 获取活动详情
func (SupportActivity) Detail(ctx context.Context, db *gorm.DB, id string) (data *models.SupportActivity, err error) {
	a := dal.Use(db).SupportActivity

	data, err = a.WithContext(ctx).
		Where(a.ID.Eq(id), a.DeletedAt.Eq(0)).
		Take()
	return data, err
}

// List 获取活动列表
func (SupportActivity) List(ctx context.Context, db *gorm.DB, name, id string, status int8, createUser string, startTime, endTime int64, page, limit int) (data []*models.SupportActivity, count int64, err error) {
	a := dal.Use(db).SupportActivity
	tx := a.WithContext(ctx).
		Where(a.DeletedAt.Eq(0))

	if name != "" {
		tx = tx.Where(a.Name.Like("%" + strings.TrimSpace(name) + "%"))
	}
	if id != "" {
		tx = tx.Where(a.ID.Eq(id))
	}
	if status != 0 {
		tx = tx.Where(a.Status.Eq(status))
	}
	if createUser != "" {
		tx = tx.Where(a.CreateUserName.Like("%" + strings.TrimSpace(createUser) + "%"))
	}
	if startTime > 0 {
		tx = tx.Where(a.StartTime.Gte(startTime))
	}
	if endTime > 0 {
		tx = tx.Where(a.EndTime.Lte(endTime))
	}

	data, count, err = tx.Order(a.ID.Desc()).FindByPage(Offset(page, limit))
	return data, count, err
}

// ChangeStatus 修改活动状态
func (SupportActivity) ChangeStatus(ctx context.Context, db *gorm.DB, id string, status int8) (err error) {
	a := dal.Use(db).SupportActivity

	_, err = a.WithContext(ctx).
		Where(a.ID.Eq(id), a.DeletedAt.Eq(0)).
		Update(a.Status, status)
	return err
}

// Delete 删除活动（软删除）
func (SupportActivity) Delete(ctx context.Context, db *gorm.DB, id string) (err error) {
	a := dal.Use(db).SupportActivity

	_, err = a.WithContext(ctx).
		Where(a.ID.Eq(id), a.DeletedAt.Eq(0)).
		Update(a.DeletedAt, time.Now().Unix())
	return err
}

// SameNameExist 检查同名活动是否存在
func (SupportActivity) SameNameExist(ctx context.Context, db *gorm.DB, name, exceptID string) (count int64) {
	a := dal.Use(db).SupportActivity
	tx := a.WithContext(ctx).
		Where(a.DeletedAt.Eq(0))

	if name != "" {
		tx = tx.Where(a.Name.Eq(strings.TrimSpace(name)))
	}
	if exceptID != "" {
		tx = tx.Where(a.ID.Neq(exceptID))
	}

	count, _ = tx.Count()
	return count
}

// GetActivityListByMaterialIDs 根据素材ID获取关联的活动列表
func (SupportActivity) GetActivityListByMaterialIDs(ctx context.Context, db *gorm.DB, materialID string) (data []*models.SupportActivity, err error) {
	a := dal.Use(db).SupportActivity

	// 查询包含该素材ID的活动（素材ID在逗号分隔的字段中）
	data, err = a.WithContext(ctx).
		Where(a.DeletedAt.Eq(0)).
		Where(a.MaterialIDs.Like("%" + materialID + "%")).
		Find()
	return data, err
}

// GetMaterialIDsList 获取活动关联的素材ID列表
func (SupportActivity) GetMaterialIDsList(ctx context.Context, db *gorm.DB, ids []string) (res []struct {
	ID          string `json:"id"`
	MaterialIDs string `json:"material_ids"`
}, err error) {
	a := dal.Use(db).SupportActivity

	err = a.WithContext(ctx).
		Where(a.DeletedAt.Eq(0)).
		Where(a.ID.In(ids...)).
		Select(a.ID, a.MaterialIDs).
		Scan(&res)
	return res, err
}

// SetMaterialIDs 仅更新素材 ID 字段
func (SupportActivity) SetMaterialIDs(ctx context.Context, db *gorm.DB, id, materialIDs string) error {
	a := dal.Use(db).SupportActivity
	_, err := a.WithContext(ctx).
		Where(a.ID.Eq(id), a.DeletedAt.Eq(0)).
		UpdateSimple(
			a.MaterialIDs.Value(materialIDs),
			a.UpdatedAt.Value(time.Now().Unix()),
		)
	return err
}
